<?php

/**
 * This is the model class for table "category".
 *
 * The followings are the available columns in table 'category':
 * @property integer $id
 * @property integer $parent_id
 * @property integer $type  1:news 2:product 3:download 4:case 5:recruit
 * @property string $name
 * @property string $alias
 * @property string $keywords
 * @property string $description
 * @property integer $sort
 * @property string $thumb
 * @property string $template
 * @property string $article_template
 * @property string $remark
 * @property integer $created_at
 * @property integer $updated_at
 */
class Category extends CActiveRecord
{
    public $level;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, alias', 'required'),
			array('parent_id, sort, created_at, updated_at, status, type, page_size', 'length', 'max'=>11),
			array('name, alias, keywords, description, template, article_template, remark', 'length', 'max'=>255),
            array(
                'thumb',
                'file','on'=>'insert',
                'allowEmpty'=>true,
                'types'=>'jpg, jpeg, gif, png, bmp', 'maxSize'=>1024 * 1024 * 10, // 10MB
                'tooLarge'=>'文件大于10M，上传失败！请上传小于10M的文件！'
            ),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, parent_id, name, alias, description, sort, page_size, template, article_template, remark, created_at, updated_at, status, keywords, thumb, type', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'parent_id' => '父类',
			'type' => Yii::t('app', 'Type'),
			'name' => '名称',
			'alias' => '别名',
            'keywords' => '关键词',
			'description' => '描述',
			'sort' => '排序',
            'thumb' => '封面',
            'page_size' => '分页',
			'template' => '分类模板',
			'article_template' => '文章模板',
			'remark' => '备注',
			'created_at' => 'Created At',
			'updated_at' => 'Updated At',
            'status' => '状态',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('parent_id',$this->parent_id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('alias',$this->alias,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('sort',$this->sort,true);
        $criteria->compare('thumb',$this->thumb,true);
		$criteria->compare('template',$this->template,true);
		$criteria->compare('article_template',$this->article_template,true);
		$criteria->compare('remark',$this->remark,true);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('updated_at',$this->updated_at,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}


    /**
     * @return mixed
     */
    protected static function _getCategories()
    {
        return $data = array_map(function ($record){return $record->attributes;},self::model()->findAll(array('order'=>'sort asc,parent_id asc')));
    }

    /**
     * @return array
     */
    public static function getCategories()
    {
        $categories = self::_getCategories();
        $familyTree = new FamilyTree($categories);
        $array = $familyTree->getDescendants(0);
        //根据字段id对数组$array进行升序排列
        return FamilyTree::arrayIndex($array,'id');
    }

    /**
     * 获取 DropDownList 数据
     * @return array
     */
    public static function getCategoriesName()
    {
        $categories = self::getCategories();
        $data = array();
        foreach ($categories as $k => $category){
            if( isset($categories[$k+1]['level']) && $categories[$k+1]['level'] == $category['level'] ){
                $name = ' ├' . $category['name'];
            }else{
                $name = ' └' . $category['name'];
            }
            if( end($categories) == $category ){
                $sign = ' └';
            }else{
                $sign = ' │';
            }
            $data[$category['id']] = str_repeat($sign, $category['level']-1) . $name;
        }
        return $data;
    }

    /**
     * @return array
     */
    public static function getMenuCategories($menuCategoryChosen=false)
    {
        $categories = self::getCategories();
        $familyTree = new FamilyTree($categories);
        $data = array();
        foreach ($categories as $k => $category){
            $parents = $familyTree->getAncectors($category['id']);
            $url = '';
            if(!empty($parents)){
                $parents = array_reverse($parents);
                foreach ($parents as $parent) {
                    $url .= '/' . $parent['alias'];
                }
            }
            if( isset($categories[$k+1]['level']) && $categories[$k+1]['level'] == $category['level'] ){
                $name = ' ├' . $category['name'];
            }else{
                $name = ' └' . $category['name'];
            }
            if( end($categories) == $category ){
                $sign = ' └';
            }else{
                $sign = ' │';
            }
            if( $menuCategoryChosen ){
                $url = '{"0":"article/index","cat":"' . $category['alias'] . '"}';
            }else{
                $url = '/'.$category['alias'];
            }
            $data[$url] = str_repeat($sign, $category['level']-1) . $name;
        }
        return $data;
    }

    /**
     * @param $id
     * @return array
     */
    public static function getDescendants($id)
    {
        $familyTree = new FamilyTree(self::_getCategories());
        return $familyTree->getDescendants($id);
    }

    /**
     * 将分类转换为数组
     * @param int $parentId
     * @param array $array
     * @param int $level
     * @param int $add
     * @param string $repeat
     * @return array
     */
    public static function getCategoryTree($parentId = 0, $array = array(), $level = 0, $add = 2, $repeat = '&nbsp;&nbsp;') {
        $str_repeat = '';
        if ($level) {
            for($j = 0; $j < $level; $j ++) {
                $str_repeat .= $repeat;
            }
        }
        $newArray = array ();
        $tempArray = array ();
        foreach ( (array) $array as $v ) {
            if ($v ['parent_id'] == $parentId) {
                $newArray [] = array (
                    'id' => $v['id'],
                    'parent_id' => $v['parent_id'],
                    'type' => $v['type'],
                    'name' => $v['name'],
                    'alias' => $v['alias'],
                    'keywords' => $v['keywords'],
                    'description' => $v['description'],
                    'sort' => $v['sort'],
                    'thumb' => $v['thumb'],
                    'page_size' => $v['page_size'],
                    'template' => $v['template'],
                    'article_template' => $v['article_template'],
                    'remark' => $v ['remark'],
                    'status' => $v['status'],
                    'created_at' => $v['created_at'],
                    'updated_at' => $v['updated_at'],
                    'str_repeat' => $str_repeat,
                    'level' => $level,
                );

                $tempArray = self::getCategoryTree ( $v ['id'], $array, ($level + $add) );
                if ($tempArray) {
                    $newArray = array_merge ( $newArray, $tempArray );
                }
            }
        }
        return $newArray;
    }

    public function beforeSave()
    {
        return parent::beforeSave(); // TODO: Change the autogenerated stub
        /*$fileThumb = CUploadedFile::getInstance($this,'thumb');
        if ($fileThumb) {
            $this->thumb = XUpload::createFile($fileThumb, $this->thumb);
        }*/
    }

    public function afterSave()
    {
        parent::afterSave(); // TODO: Change the autogenerated stub
        $this->thumb = $this->thumb;
    }

}
